//
//  LESwitcher.m
//  WindRunner
//
//  Created by leeqb on 3/28/15.
//  Copyright (c) 2015 poweropt. All rights reserved.
//

#import "LESwitcher.h"

@implementation LESwitcher

- (void)setOn:(BOOL)on
{
    _on = on;
    
    CGRect rectOn = _switcherOnView.frame;
    CGRect rectOff = _switcherOffView.frame;
    if(_on) {
        [self bringSubviewToFront:_switcherOnView];
        rectOn.origin.x = 0;
        rectOff.origin.x = -rectOff.size.width;
        _switcherOnView.frame = rectOn;
        _switcherOffView.frame = rectOff;
    } else {
        [self bringSubviewToFront:_switcherOffView];
        rectOn.origin.x = rectOn.size.width;
        rectOff.origin.x = 0;
        _switcherOffView.frame = rectOff;
        _switcherOnView.frame = rectOn;
    }
}

- (void)awakeFromNib
{
    _on = YES;
    [[NSBundle mainBundle] loadNibNamed:@"LESwitcher" owner:self options:nil];
    _switcherOnView.userInteractionEnabled = YES;
    _switcherOffView.userInteractionEnabled = YES;
    [self addSubview:_switcherOnView];
    [self addSubview:_switcherOffView];
    self.layer.masksToBounds = YES;
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onSwitch)];
    [_switcherOnView addGestureRecognizer:tapGesture];
    
    tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onSwitch)];
    [_switcherOffView addGestureRecognizer:tapGesture];
}

- (void)onSwitch
{
    CGRect rectOn = _switcherOnView.frame;
    CGRect rectOff = _switcherOffView.frame;
    
    if(_on) {
        _on = NO;
        [self bringSubviewToFront:_switcherOffView];
        rectOn.origin.x = rectOn.size.width;
        rectOff.origin.x = 0;
        _switcherOffView.frame = rectOff;
        _switcherOnView.frame = rectOn;
    } else {
        _on = YES;
        [self bringSubviewToFront:_switcherOnView];
        rectOn.origin.x = 0;
        rectOff.origin.x = -rectOff.size.width;
        _switcherOnView.frame = rectOn;
        _switcherOffView.frame = rectOff;
    }
    
    if(_delegate && [_delegate respondsToSelector:@selector(onSwitch:)]) {
        [_delegate onSwitch:_on];
    }
}

@end
